package com.xinchen.gufeiwulian.ui.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatSpinner
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.AppUtils
import com.maple.base.base.BaseFragment
import com.maple.common.widget.spinner.UnitSpinnerAdapter
import com.maple.model.data.AccountType
import com.maple.utils.ext.afterTextChanged
import com.maple.utils.ext.toGone
import com.maple.utils.ext.toVisible
import com.maple.utils.store.AppDBHelper
import com.maple.utils.util.DeviceUtils
import com.maple.utils.util.LogUtils
import com.maple.utils.util.UIUtils
import com.xinchen.gufeiwulian.R
import com.xinchen.gufeiwulian.ui.activity.HomeActivity
import com.xinchen.gufeiwulian.vm.AccountViewModel
import java.util.WeakHashMap

class LoginFragment : BaseFragment() {

    private var etAccount: EditText? = null
    private var etPassword: EditText? = null
    private var ibtnAccountClear: ImageButton? = null
    private var ibtnPasswordEye: ImageButton? = null
    private var btnLogin: Button? = null

    private var cbRememberPwd: CheckBox? = null
    private var llRememberPwd: LinearLayout? = null
    private var tvVersionName: TextView? = null

    private var spUnit: AppCompatSpinner? = null

    private val unitAdapter: UnitSpinnerAdapter by lazy {
        UnitSpinnerAdapter(requireContext()).apply {
            this.setData(listOf(AccountType.HINT.typeName,AccountType.CF.typeName,AccountType.YS.typeName,AccountType.CZ.typeName))
        }
    }

    private val eyeShowDrawable by lazy {
        UIUtils.getDrawable(R.drawable.ic_eye_show)
    }
    private val eyeHideDrawable by lazy {
        UIUtils.getDrawable(R.drawable.ic_eye_hide)
    }

    private val viewModel by viewModels<AccountViewModel>()

    override fun hasNavController(): Boolean  = true
    override fun getLayoutId(): Int = R.layout.fragment_login



    override fun initView(view: View, savedInstanceState: Bundle?) {
        super.initView(view, savedInstanceState)
        tvVersionName = view.findViewById(R.id.tv_version_name)
        tvVersionName?.text = "版本 ${AppUtils.getAppVersionName()}"
        tvVersionName?.setOnClickListener {
            if(UIUtils.isFastClick()) {
                viewModel.isDebugModel = true
                showToast("测试模式已打开")
            }
        }
        view.findViewById<ImageView>(R.id.iv_setting)?.setOnClickListener {
            onSetting()
        }

        cbRememberPwd = view.findViewById(R.id.cb_remember_pwd)
        llRememberPwd = view.findViewById(R.id.ll_remember_pwd)
        if(AppDBHelper.getRememberPwd()) {
            cbRememberPwd?.isChecked = true
        }
        llRememberPwd?.setOnClickListener {
            cbRememberPwd?.isChecked = !(cbRememberPwd?.isChecked?:false)

            val isRememberPwd = cbRememberPwd?.isChecked
            LogUtils.logGGQ("===isRememberPwd====>>>${isRememberPwd}")
            AppDBHelper.saveRememberPwd(isRememberPwd)
        }
        etAccount = view.findViewById(R.id.et_account)
        etAccount?.setText(AppDBHelper.getAccount())
        etPassword = view.findViewById(R.id.et_password)
        etPassword?.setText(AppDBHelper.getPassword())
        ibtnAccountClear = view.findViewById(R.id.ibtn_account_clear)
        ibtnPasswordEye = view.findViewById(R.id.ibtn_password_eye)
        spUnit = view.findViewById(R.id.sp_unit)
        spUnit?.adapter = unitAdapter
        val platform: Int = AppDBHelper.getPlatform()
        spUnit?.setSelection(unitAdapter.getPositionByName(getPlatformName(platform)),true)
        LogUtils.logGGQ("===platform====>>${getPlatformName(platform)}")

        btnLogin = view.findViewById(R.id.btn_login)
        etAccount?.afterTextChanged {
            if(!TextUtils.isEmpty(it)) {
                ibtnAccountClear?.toVisible()
            } else {
                ibtnAccountClear?.toGone()
            }
        }

        etPassword?.afterTextChanged {
            if(!TextUtils.isEmpty(it)) {
                ibtnPasswordEye?.toVisible()
            } else {
                ibtnPasswordEye?.toGone()
            }
        }

        btnLogin?.setOnClickListener {
            onLogin()
        }
        ibtnAccountClear?.setOnClickListener {
            etAccount?.setText("")
        }
        ibtnPasswordEye?.setOnClickListener {
            if(etPassword == null) return@setOnClickListener
            UIUtils.editTransformation(etPassword!!,it as ImageView,eyeShowDrawable,eyeHideDrawable)
        }
    }
    override fun initData(savedInstanceState: Bundle?) {
        viewModel.defUI.showDialog.observe(this, Observer {
            showLoading()
        })

        viewModel.defUI.dismissDialog.observe(this, Observer {
            dismissLoading()
        })

        viewModel.defUI.toastEvent.observe(this, Observer {
            showToast(it)
        })
        viewModel.loginEvent.observe(this, Observer {
            onStartActivity(HomeActivity::class.java, isFinish = true)
        })

//        etAccount?.setText("CSSYCFQY")
//        etPassword?.setText("1qaz!QAZ")
//        etAccount?.setText("ZMDSZXCF0000000001")
//        etPassword?.setText("123456Aa.")

        etAccount?.setText("HBSCF0000000000001")
        etPassword?.setText("HBqwer1234.")
    }

    private fun onLogin() {
        val account = etAccount?.text.toString().trim()
        val password = etPassword?.text.toString().trim()
        if(TextUtils.isEmpty(account)) {
            showToast("请输入用户名")
            return
        }
        if(TextUtils.isEmpty(password)) {
            showToast("请输入密码")
            return
        }
        val unit = spUnit?.selectedItem.toString()
        if(TextUtils.equals(AccountType.HINT.typeName,unit)) {
            showToast(unit)
            return
        }

        val imei = DeviceUtils.getIMEI(requireContext())
        if(TextUtils.isEmpty(imei)) {
            showToast("登录设备异常,请联系客服")
            return
        }

        LogUtils.logGGQ("====imei===>>${imei}")

        val params: WeakHashMap<String, Any> = WeakHashMap()
        val platform = getPlatform(unit)
        params.put("username", account)
        params.put("password", password)
        params.put("deviceid", imei)
        params.put("platform", platform)


        viewModel.onLogin(account,password,cbRememberPwd?.isChecked?:false,platform,params)

    }

    private fun getPlatform(typeName: String): Int {
        if(TextUtils.equals(typeName,AccountType.CF.typeName)) {
            return AccountType.CF.type
        } else if(TextUtils.equals(typeName,AccountType.YS.typeName)) {
            return AccountType.YS.type
        } else if(TextUtils.equals(typeName,AccountType.CZ.typeName)) {
            return AccountType.CZ.type
        } else if(TextUtils.equals(typeName,AccountType.HBJ.typeName)) {
            return AccountType.HBJ.type
        } else {
            return AccountType.HINT.type
        }
    }

    private fun getPlatformName(platform: Int): String {
        if(platform == AccountType.CF.type) {
            return AccountType.CF.typeName
        } else if(platform == AccountType.YS.type) {
            return AccountType.YS.typeName
        } else if(platform == AccountType.CZ.type) {
            return AccountType.CZ.typeName
        } else if(platform == AccountType.HINT.type) {
            return AccountType.HBJ.typeName
        } else {
            return AccountType.HINT.typeName
        }
    }

    private fun onSetting() {
        navController?.navigate(R.id.action_loginFragment_to_settingFragment)
    }
}